package com.lori.netshop.service.imp;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.lori.netshop.service.PicUploadService;
import com.lori.netshop.util.FilenameUtil;


@Service
public class PicUploadServiceimp implements PicUploadService{
	//获得properties的值
	@Value("${BASEPATH}")
	private String BASEPATH;
	/**
	 * 功能：图片上传
	 */
	public Map picUpload(MultipartFile uploadFile){
		Map map = new HashMap();
		try {
			if(uploadFile == null)return null;
			//获得原文件名
			String originalname = uploadFile.getOriginalFilename();
			//获得新文件名
			String filename = FilenameUtil.getFilename()+originalname.substring(originalname.lastIndexOf("."));
			//新文件路径
			String format = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
			File file = new File(BASEPATH+"/"+format);
			if(!file.exists())file.mkdirs();
			File file2 = new File(file,filename);
			//获得输入流
			FileOutputStream fos = new FileOutputStream(file2);
			//获得输入流
			InputStream inputStream = uploadFile.getInputStream();
			byte[] byt = new byte[1024];
			//存储文件
			int len = 0;
			while((len = inputStream.read(byt)) != -1){
				fos.write(byt, 0, len);
			}
			map.put("error", 0);
			map.put("url", "upload/"+format+"/"+filename);
			return map;
		} catch (Exception e) {
			map.put("error", 1);
			map.put("url", "图片上传失败");
			e.printStackTrace();
			return map;
		}
	}
}
